<?php

namespace App\Models;

use App\Models\BaseModel;
use Illuminate\Auth\Authenticatable;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Facades\JWTFactory;

use Illuminate\Database\Eloquent\Model;

use Encore\Admin\Auth\Database\Administrator;

use SimpleSoftwareIO\QrCode\Generator;

class Member extends BaseModel implements AuthenticatableContract, JWTSubject
{
    use  Authenticatable;

    protected $jwtCustom = [];

    protected $primaryKey = 'member_id';

    protected $table = "members";

    protected $visible = ['member_id', 'username', 'password', 'nickname', 'openid', 'sex', 'headimgurl', 'email', 'mobile', 'created_at', 'updated_at'];

    protected $fillable = ['username', 'password', 'nickname', 'openid', 'sex', 'headimgurl', 'email', 'mobile'];

    protected $appends = [];


    protected $casts = [
        'created_at' => 'Y-m-d H:i:s',
        'updated_at' => 'Y-m-d H:i:s',
    ];

    /**
     * 绑定信息
     * @return \Illuminate\Database\Eloquent\Relations\hasOne
     */
    // public function bind()
    // {
    //     return $this->hasOne(MemberBindAdmin::class, 'member_id');
    // }

    protected static function boot()
    {
        parent::boot();
        // self::deleting(function ($model) {
        //     $model->bind()->delete();
        // });
    }

    public static function login($params)
    {
        $model = self::select('member_id', 'username', 'nickname', 'openid', 'sex', 'headimgurl', 'mobile', 'created_at', 'updated_at')->where(['username' => $params['username']])->first();

        if (!$model)
        {
            $res['msg'] = '无账户';
            return $res;
        }

        $res = $model->toArray();
        $res['token'] = \Auth::guard('member')->fromUser($model);

        return $res;
    }

    public static function logout()
    {
        try {

            // 获取当前token
            if ($token = JWTAuth::getToken()) {
                // 卸载当前用户的token
                JWTAuth::invalidate($token);

                return true;
            }
        } catch (JWTException $e) {
            return false;
        }

        return false;
    }

    // jwt 需要实现的方法
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    // jwt 需要实现的方法, 一些自定义的参数
    public function getJWTCustomClaims()
    {
        return [];
    }

    // 获取积分明细列表
    public static function getScoreList(array $attributes)
    {
        extract($attributes);

        $member =  \Auth::guard('member')->user();

        $model = MemberScoreLog::where('member_id', $member->member_id);

        $total = $model->count();

        $model->orderBy('id', 'DESC');

        if (isset($per_page))
        {
            $data = $model->paginate($per_page)->toArray();

            if (!empty($data['data']))
            {
                foreach ($data['data'] as $key=>$val)
                {
                    if (!$val) continue;

                    $data['data'][$key]['created_at'] = date('Y-m-d H:i:s', strtotime($val['created_at']));
                    $data['data'][$key]['updated_at'] = date('Y-m-d H:i:s', strtotime($val['updated_at']));
                }
            }

            return self::formatBody(['list' => $data['data'], 'paged' => self::formatPaged($page, $per_page, $total)]);
        }
        else
        {
            $data = $model->get()->toArray();

            if (!empty($data))
            {
                foreach ($data as $key=>$val)
                {
                    if (!$val) continue;

                    $data[$key]['created_at'] = date('Y-m-d H:i:s', strtotime($val['created_at']));
                    $data[$key]['updated_at'] = date('Y-m-d H:i:s', strtotime($val['updated_at']));
                }
            }

            return self::formatBody(['list' => $data]);
        }

    }

    // 更新会员信息
    public static function setMemberInfo(array $attributes)
    {
        extract($attributes);

        $member = \Auth::guard('member')->user();

        if (!$member)
        {
            return self::formatError(400, '获取会员信息失败');
        }

        if (!empty($mobile))
        {
            $member->mobile = $mobile;
        }

        if (!empty($email))
        {
            $member->email = $email;
        }

        if (!empty($committees))
        {
            $member->committees = $committees;
        }

        if (!empty($name))
        {
            $member->name = $name;
        }

        if (!empty($openid))
        {
            $member->openid = $openid;
        }


        if (!$member->save())
        {
            return self::formatError(400, '更新会员信息失败');
        }

        return self::formatBody(['data' => $member], '保存成功');
    }





}
